import { createRouter, createWebHashHistory } from 'vue-router'
import { getToken } from '@/utils/auth'
import Layout from '@/layout/index.vue'

const routes = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/login/index.vue'),
        meta: { title: '登录' }
    },
    {
        path: '/',
        component: Layout,
        redirect: '/dashboard',
        children: [
            {
                path: 'dashboard',
                name: 'Dashboard',
                component: () => import('@/views/dashboard/index.vue'),
                meta: { title: '数据看板', icon: 'Odometer' }
            },
            {
                path: 'user',
                name: 'User',
                component: () => import('@/views/system/user/index.vue'),
                meta: { title: '用户管理', icon: 'User' }
            },
            {
                path: 'role',
                name: 'Role',
                component: () => import('@/views/system/role/index.vue'),
                meta: { title: '角色管理', icon: 'UserFilled' }
            },
            {
                path: 'product',
                name: 'Product',
                component: () => import('@/views/product/name/index.vue'),
                meta: { title: '品名管理', icon: 'Document' }
            }
        ]
    },
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: () => import('@/views/error/404.vue'),
        meta: { title: '404' }
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
    const token = getToken()

    if (to.path === '/login') {
        if (token) {
            next('/')
        } else {
            next()
        }
    } else {
        if (token) {
            next()
        } else {
            next('/login')
        }
    }
})

export default router 